//
//  AccountProductDetailView.m
//  NOAHWM
//
//  Created by Ryan on 13-6-22.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "AccountProductDetailView.h"
#import "AccountProductDetailCell.h"
#import "NYMemberCenterDataManager.h"
#import "JSON.h"

#define kAccountProductFieldFileName @"AccountProductField"

@interface AccountProductDetailView()

@property (nonatomic, retain) NSArray *localFieldArray;
@property (nonatomic, retain) NSMutableArray *proFieldArray;
@property (nonatomic, retain) NSMutableArray *fundFieldArray;

@end

@implementation AccountProductDetailView

@synthesize detailScrollView,proInfoTableView,fundInfoTableView,pageControl;
@synthesize localFieldArray,proFieldArray,fundFieldArray;
@synthesize accountProductDetail;

#pragma mark - Public methods
- (void)callServerToGetAccountProductDetailWithAccountId:(NSString *)accountId
                                               productId:(NSString *)productId
{
    NSString *suburl = [NSString stringWithFormat:kAccountProductDetailUrl,@"jsonp",accountId,productId,@""];
    suburl = [suburl stringByAppendingString:@"app000027"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
}


#pragma mark - UIView methods

- (void)awakeFromNib
{
    [super awakeFromNib];
    NSString *path = [[NSBundle mainBundle] pathForResource:kAccountProductFieldFileName ofType:@"plist"];
    self.localFieldArray = [NSArray arrayWithContentsOfFile:path];
    [self.detailScrollView setContentSize:CGSizeMake(detailScrollView.frame.size.width*2, detailScrollView.frame.size.height)];
    self.pageControl.currentPage = 0;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [proFieldArray release];
    [fundFieldArray release];
    [accountProductDetail release];
    [localFieldArray release];
    [detailScrollView release];
    [proInfoTableView release];
    [fundInfoTableView release];
    [pageControl release];
    [super dealloc];
}

#pragma mark - UIScrollViewDeletgate methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if([scrollView isMemberOfClass:[UIScrollView class]])
    {
        NSInteger page = floor((scrollView.contentOffset.x - scrollView.frame.size.width / 2) / scrollView.frame.size.width) + 1;
        self.pageControl.currentPage = page;
    }
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == proInfoTableView)
    {
        return self.proFieldArray.count;
    }
    else
    {
        return self.fundFieldArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if(tableView == fundInfoTableView && indexPath.row == 0)
//    {
//        static NSString *usernameCellIdentify = @"usernameCellIdentify";
//        UITableViewCell *usernameCell = [tableView dequeueReusableCellWithIdentifier:usernameCellIdentify];
//        if(nil == usernameCell)
//        {
//            usernameCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:usernameCellIdentify] autorelease];
//            usernameCell.selectionStyle = UITableViewCellSelectionStyleNone;
//            
//            UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.rowHeight)];
//            bgImageView.tag = 101;
//            bgImageView.image = [UIImage imageNamed:@"bg_selection@2x.png"];
//            [usernameCell.contentView addSubview:bgImageView];
//            [bgImageView release];
//            
//            UILabel *keyLabel = [[UILabel alloc] initWithFrame:CGRectMake(25.f, 0, 120.f, tableView.rowHeight)];
//            keyLabel.tag = 99;
//            keyLabel.backgroundColor = [UIColor clearColor];
//            keyLabel.font = [UIFont systemFontOfSize:12.f];
//            keyLabel.textColor = [UIColor colorWithRed:37.f/255 green:37.f/255 blue:37.f/255 alpha:1.f];
//            [usernameCell.contentView addSubview:keyLabel];
//            [keyLabel release];
//            
//            UILabel *usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(145.f, 0, 165.f, tableView.rowHeight)];
//            usernameLabel.tag = 100;
//            usernameLabel.backgroundColor = [UIColor clearColor];
//            usernameLabel.font = [UIFont systemFontOfSize:12.f];
//            usernameLabel.textColor = [UIColor colorWithRed:245.f/255 green:100.f/255 blue:35.f/255 alpha:1.f];
//            [usernameCell.contentView addSubview:usernameLabel];
//            [usernameLabel release];
//        }
//        UILabel *keyLabel = (UILabel *)[usernameCell.contentView viewWithTag:99];
//        keyLabel.text = @"用户名";
//        UILabel *usernameLabel = (UILabel *)[usernameCell.contentView viewWithTag:100];
//        usernameLabel.text = [NYMemberCenterDataManager sharedManager].loginMember.userName;
//        
//        UIImageView *bgImageView = (UIImageView *)[usernameCell.contentView viewWithTag:101];
//        if(indexPath.row%2 == 0)
//        {
//            bgImageView.hidden = NO;
//        }
//        else
//            bgImageView.hidden = YES;
//        return usernameCell;
//    }
//    else
//    {
        static NSString *cellIdentify = @"cellIdentify";
        
        AccountProductDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        if(nil == cell)
        {
            NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"AccountProductDetailCell" owner:self options:nil];
            cell = [nibs lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSDictionary *dict = nil;
        if(tableView == proInfoTableView)
        {
            dict = [self.proFieldArray objectAtIndex:indexPath.row];
        }
        else
        {
            dict = [self.fundFieldArray objectAtIndex:indexPath.row];
        }
        cell.keyLabel.text = [dict objectForKey:@"realName"];
        cell.valueLabel.text = [NSString stringWithFormat:@"%@",[self.accountProductDetail valueForKey:[dict objectForKey:@"fieldName"]]];
        if(indexPath.row%2 == 0)
        {
            cell.bgImageView.hidden = NO;
        }
        else
            cell.bgImageView.hidden = YES;
        
        return cell;
//    }
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        for(NSString *key in [dict allKeys])
        {
            id value = [dict objectForKey:key];
            @try {
                [self.accountProductDetail setValue:value forKey:key];
            }
            @catch (NSException *exception) {
                NSLog(@"试图添加不存在的key: %@到NYAccountProductDetail实例中.",key);
            }
        }
        
        self.proFieldArray = [NSMutableArray array];
        self.fundFieldArray = [NSMutableArray array];
        for(NSDictionary *dict in self.localFieldArray)
        {
            if([[dict objectForKey:@"isProductInfo"] boolValue])
            {
                //产品信息
                if([[dict objectForKey:@"PE/VC"] boolValue] &&
                   [[dict objectForKey:@"类固定收益"] boolValue] &&
                   [[dict objectForKey:@"房地产基金"] boolValue] &&
                   [[dict objectForKey:@"资管"] boolValue] &&
                   [[dict objectForKey:@"正行"] boolValue])
                {
                    [self.proFieldArray addObject:dict];
                }
            }
            else
            {
                //资金信息
                [self.fundFieldArray addObject:dict];
            }
        }
        
        
        [self.proInfoTableView reloadData];
        [self.fundInfoTableView reloadData];
    }
    else
    {
//        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}


@end
